/**
 *@author Ivam Henrique Marques dos Santos
 *        email: ivam.santos@skytef.com.br
 *        skype: ivam.santos.skytef
 *        telefone: +55 11 96214-7543
 * */

package br.skytef.stmanager.beans;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

import br.skytef.stmanager.daos.UsuarioDao;
import br.skytef.stmanager.entities.UsuarioEntity;

/**
 * Class Controller LoginBean
 * */

@ManagedBean(name="LoginBean")
@SessionScoped
public class LoginBean {  

	/**
	 * Campos com seus respectivos Getters e Setters.	  
	 */

	private UsuarioEntity usuarioBD;
	public UsuarioEntity getUsuarioBD() {return usuarioBD;}
	public void setUsuarioBD(UsuarioEntity usuarioBD) {this.usuarioBD = usuarioBD;}

	private String username; 
	public String getUsername() {return username;}
	public void setUsername(String username) {this.username = username;}
	
	private String password;
	public String getPassword() {return password;}
	public void setPassword(String password) {this.password = password;}

	private HttpSession session;

	public String getMsg() {return msg;}
	public void setMsg(String msg) {this.msg = msg;}
	private String msg;

	public String getVisible() {return visible;}
	public void setVisible(String visible) {this.visible = visible;}
	private String visible = "false";
	/**
	 * Métodos de controle.
	 */	
	@PostConstruct
	public void init() {
		//Chamado só quando o managed bean é colocado no escopo view,
		//e não a cada requisição como acontecia com o escopo request
		usuarioBD = new UsuarioEntity();
	}

	@PreDestroy
	public void destroy() {
		/* chamado quando outra view for chamada através do UIViewRoot.setViewId(String viewId) */
	}

	/**
	 * @param ActionEvent
	 * */
	public void login(ActionEvent actionEvent) throws IOException {  
		@SuppressWarnings("unused")
		boolean loggedIn = false;    

		if(username.toLowerCase()!= null && password.toLowerCase() != null && !username.toLowerCase().equals("") && !password.toLowerCase().equals("")) {  
			usuarioBD = new UsuarioDao().buscar(username.toLowerCase());

			if (usuarioBD != null){
				if (usuarioBD.getLogin().equals(username.toLowerCase())  && usuarioBD.getSenha().equals(password.toLowerCase())){
					loggedIn = true; 
					FacesContext ctx = FacesContext.getCurrentInstance();
					session = (HttpSession) ctx.getExternalContext().getSession(false);
					session.setAttribute("usuario", usuarioBD);
					System.out.println(session.getId());					
					ctx.getExternalContext().redirect("dashboard.xhtml");
					setMsg("Bem-vindo" + username);
				}

				if (!(usuarioBD.getSenha().equals(password.toLowerCase()))){
					FacesContext.getCurrentInstance().getExternalContext()  
					.redirect("../");
					setMsg("Senha inválida");
					setVisible("true");
				}
			}
		}

		if (usuarioBD == null || username.toLowerCase().equals("") || password.toLowerCase().equals("")){
			FacesContext.getCurrentInstance().getExternalContext()  
			.redirect("../");
			setMsg("Login inválido : Usuário não encontrado/"
					+ "Campo(s) não preenchido(s).");
			setVisible("true");
		}	
	}

	public void encerraSessao() {
		try {
			FacesContext ctx = FacesContext.getCurrentInstance();
			session = (HttpSession) ctx.getExternalContext().getSession(false);
			session.setAttribute("usuario", null);
			ctx.getExternalContext().redirect(ctx.getExternalContext().getRequestContextPath() + "/");
			session.invalidate();
		} catch (Exception e) {
		}
	}
}


